<template>
  <el-container style="padding: 20px">
    <el-main>
      <el-card>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span style="font-weight: bold">{{
            isChartView ? '核查任务统计图' : '核查任务列表'
          }}</span>
          <el-button type="primary" @click="toggleView">
            切换为{{ isChartView ? '任务列表' : '任务图表' }}
          </el-button>
        </div>

        <!-- 图表视图 -->
        <div v-if="isChartView" ref="chartContainer" class="chart-container" />

        <!-- 任务列表视图 -->
        <div v-else>
          <el-table
            :data="tasks"
            border
            style="width: 100%; margin-top: 20px"
            v-loading="loading"
          >
            <el-table-column prop="id" label="任务ID" width="80" />
            <el-table-column prop="checkerId" label="核查员ID" width="100" />
            <el-table-column
              prop="vaccineNumbering"
              label="疫苗编号"
              width="200"
            />
            <el-table-column prop="assignedAt" label="分配时间" width="200">
              <template #default="{ row }">{{
                formatDate(row.assignedAt)
              }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)">{{
                  row.status
                }}</el-tag>
              </template>
            </el-table-column>

            <!-- 邮箱提醒按钮单独列 -->
            <el-table-column label="邮箱提醒" width="120">
              <template #default="{ row }">
                <el-button
                  v-if="row.status === 'pending'"
                  size="mini"
                  type="info"
                  @click="sendEmailReminder(row.id)"
                >
                  邮箱提醒
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[5, 10, 20]"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            style="margin-top: 20px; text-align: right"
          />
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const page = ref(1)
const pageSize = ref(5)
const total = ref(0)
const loading = ref(false)
const tasks = ref([])

const isChartView = ref(true)
const chartContainer = ref(null)
let chartInstance = null

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 根据任务状态返回标签类型
const statusTagType = (status) => {
  switch (status) {
    case '未开始':
      return 'info'
    case '进行中':
      return 'warning'
    case '已完成':
      return 'success'
    case '异常':
      return 'danger'
    default:
      return ''
  }
}

// 请求任务列表分页数据
const fetchTasks = async () => {
  loading.value = true
  try {
    const res = await axios.get('http://127.0.0.1:8181/checkTasks/list', {
      params: {
        page: page.value,
        pageSize: pageSize.value,
      },
    })
    if (res.data.code === 0) {
      tasks.value = res.data.data.data || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error('获取任务列表失败')
    }
  } catch (error) {
    ElMessage.error('获取任务列表异常')
  } finally {
    loading.value = false
  }
}

// 拉取任务状态统计数据并渲染图表
const fetchStatusSummaryAndRenderChart = async () => {
  try {
    const res = await axios.get(
      'http://127.0.0.1:8181/checkTasks/statusSummary'
    )
    if (res.data.code === 0) {
      const statusMap = res.data.data || {}
      renderChart(statusMap)
    } else {
      ElMessage.error('获取状态统计失败')
    }
  } catch (error) {
    ElMessage.error('获取状态统计异常')
  }
}

const renderChart = (statusMap) => {
  if (!chartContainer.value) return
  if (chartInstance) {
    chartInstance.dispose()
  }
  chartInstance = echarts.init(chartContainer.value)

  const data = Object.entries(statusMap).map(([status, value]) => ({
    name: status,
    value,
  }))

  const option = {
    title: {
      text: '核查任务状态统计',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      bottom: 0,
    },
    series: [
      {
        name: '任务状态',
        type: 'pie',
        radius: '60%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }

  chartInstance.setOption(option)
  chartInstance.resize()
}

// 分页页码变化
const handlePageChange = (newPage) => {
  page.value = newPage
  fetchTasks()
}

// 分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  page.value = 1
  fetchTasks()
}

// 切换视图
const toggleView = async () => {
  isChartView.value = !isChartView.value
  if (isChartView.value) {
    await nextTick()
    fetchStatusSummaryAndRenderChart()
  } else {
    fetchTasks()
  }
}

// 邮箱提醒按钮点击事件，调用后端接口发送邮件
const sendEmailReminder = async (taskId) => {
  try {
    const res = await axios.post(
      'http://127.0.0.1:8181/users/sendEmailReminder',
      null,
      {
        params: { taskId },
      }
    )
    if (res.data.code === 0) {
      ElMessage.success('邮件发送成功')
    } else {
      ElMessage.error(res.data.msg || '邮件发送失败')
    }
  } catch (error) {
    ElMessage.error('邮件发送异常')
  }
}

// 窗口大小改变时调整图表大小
const resizeChart = () => {
  chartInstance?.resize()
}

onMounted(async () => {
  if (isChartView.value) {
    await fetchStatusSummaryAndRenderChart()
  } else {
    await fetchTasks()
  }
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}
</style>
